package foodType

import (
	"hotel_Manager_Api/model/dbModel"
	"hotel_Manager_Api/model/dbEngin"
	"github.com/martini-contrib/encoder"
	"github.com/go-martini/martini"
	"strconv"
	"github.com/go-xorm/xorm"
	"hotel_Manager_Api/model/dto"
	"github.com/deckarep/golang-set"
	"hotel_Manager_Api/util"
)

func NewFoodType(foodType dbModel.FoodType)(int,error){
	db:=dbEngin.GetEnging();
	command := "INSERT INTO `food_type` (`name`,`tagId`,`orderId`) select ?,?,max(orderId)+1 from `food_type`"
	_, err :=db.Exec(command,foodType.Name,foodType.TagId)
	if(err!=nil){
		return 500,err
	}
	return 201,nil
}

func GetAllFoodType(enc encoder.Encoder)(int,[]byte,error)  {
	db:=dbEngin.GetEnging()
	types := make([]dbModel.FoodType,0);
	err :=db.Asc("orderId").Find(&types);
	if(err!=nil){
		return 500,nil,err
	}

	ids := mapset.NewSet()
	for _,element := range types{
		if element.TagId>0{
			ids.Add(element.TagId)
		}
	}

	idsSlice := ids.ToSlice()
	tags := make([]dbModel.Tag,len(idsSlice))
	if(len(idsSlice)>0){
		err = db.In("id",idsSlice).Find(&tags)
		if(err!=nil){
			return 500,nil,err
		}
	}
	entities := joinFoodTypeTag(types,tags)

	bytes := encoder.Must(enc.Encode(entities))
	return 200,bytes,nil;
}

func EditFoodType(params martini.Params,foodType dbModel.FoodType,db *xorm.Engine)int {
	idStr:=params["id"];
	i,err := strconv.ParseInt(idStr,10,16);
	if(err!=nil){
		return 400
	}
	id:=int32(i)
	foodType.Id = id
	_,err = db.Id(id).Update(foodType)
	if(err!=nil){
		return 500
	}
	return 200
}

func DeleteFoodType(params martini.Params,db *xorm.Engine) int {
	id,err := util.ParamaterToInt16(params,"id")
	if(err!=nil){
		return 400
	}
	_,err =db.Id(id).Delete(dbModel.FoodType{})
	if(err != nil){
		return 500;
	}
	return 200
}

func joinFoodTypeTag(foodTypes []dbModel.FoodType,tags []dbModel.Tag) []dto.FoodTypeEntity  {
	dic := make(map[int16]dbModel.Tag)
	for _,element := range tags{
		dic[element.Id] = element
	}
	foodTypeEntities := make([]dto.FoodTypeEntity,len(foodTypes))
	for i,foodType := range foodTypes{
		foodTypeEntities[i] = dto.FoodTypeEntity{foodType,dic[foodType.TagId]}
	}
	return foodTypeEntities
}

func ChangeOrder(changeOrderDto dto.ChangeOrderDto,db *xorm.Engine)(int,error)  {
	foodType := new(dbModel.FoodType)
	foodType.OrderId = changeOrderDto.Item1.OrderId;
	session := db.NewSession()
	_,err := db.Id(changeOrderDto.Item1.Id).Cols("orderId").Update(foodType)
	if err!= nil{
		session.Rollback()
		return 500,err
	}
	foodType.OrderId = changeOrderDto.Item2.OrderId
	_,err = db.Id(changeOrderDto.Item2.Id).Cols("orderId").Update(foodType)
	if err!= nil{
		session.Rollback()
		return 500,err
	}
	session.Commit()
	return 200,nil

}